import random

class TDMA:
    def __init__(self, num_nodes, num_slots):
        self.num_nodes = num_nodes
        self.num_slots = num_slots
        self.schedule = [[0] * num_slots for _ in range(num_nodes)]  # 初始化每个节点的时隙调度表，0表示不发送

    def set_node_schedule(self, node_id, schedule):
        if len(schedule) == self.num_slots:
            self.schedule[node_id] = schedule
        else:
            raise ValueError("时间槽预定列表长度与时隙数不符")

    def simulate_transmissions(self):
        total_throughput = 0
        for timeslot in range(self.num_slots):
            can_transmit = True
            for node_id in range(self.num_nodes):
                if self.schedule[node_id][timeslot] == 1:  # 如果当前时隙需要节点发送
                    delay = random.randint(1, 5)  # 随机选择发送时延，1到5个时隙
                    if timeslot + delay >= self.num_slots:
                        can_transmit = False  # 发送时延超出时隙范围，无法发送
                        break
            if can_transmit:
                total_throughput += 1

        return total_throughput

# 主程序
if __name__ == "__main__":
    num_nodes = 5
    num_slots = 10000  # 修改为10000个时隙

    # 初始化 TDMA 系统
    tdma_system = TDMA(num_nodes, num_slots)

    # 为每个节点设置预定的时隙调度
    for node_id in range(num_nodes):
        schedule = [0] * num_slots  # 初始化每个节点的调度表，全部初始化为不发送
        # 随机预定部分时隙为发送状态
        for i in range(num_slots):
            if random.random() < 0.4:  # 50%的概率将时隙设为发送状态
                schedule[i] = 1
        tdma_system.set_node_schedule(node_id, schedule)

    # 模拟传输并计算总吞吐量
    total_throughput = tdma_system.simulate_transmissions()

    # 保存吞吐量到文件
    output_file = 'rewards/only_TDMA2.txt'
    with open(output_file, 'w') as f:
        f.write(str(total_throughput))

    print(f"模拟完成，吞吐量为: {total_throughput}，结果已保存至文件: {output_file}")
